package com.mezz.bones.framework.web.util;

import cn.hutool.core.io.resource.ResourceUtil;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

/**
 * @author mezz
 * @date 2023-01-17 15:26
 * @description:
 */
@Slf4j
public class Ip2RegionUtils {

  private static byte[] cBuff;

  //国家|区域|省份|城市|ISP
  public static String ip2Region(String ip) {

    // 1、从 dbPath 加载整个 xdb 到内存。
    initBuff();

    // 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
    Searcher searcher;
    try {
      searcher = Searcher.newWithBuffer(cBuff);
    } catch (Exception e) {
      log.error("failed to create content cached searcher",e);
      return "";
    }

    // 2、查询
    try {
      return searcher.search(ip);
    } catch (Exception e) {
      log.error("failed to search ip ({})", ip);
    }

    return "";
  }

  private static void initBuff() {

    if(cBuff != null){
      return;
    }

    try {
      cBuff = ResourceUtil.readBytes("ip2region.xdb");
    } catch (Exception e) {
      log.error("failed to load content from={}", "ip2region.xdb", e);
    }
  }
}
